<?php
session_start();
function getIP()
{
    static $realip;
    if (isset($_SERVER)) {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")) {
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    return $realip;
}


if ($_SESSION["captcha_pass"] == false) echo '999';
else if($_SESSION["captcha_pass"] == true){
    $question = addslashes($_POST['question']);
    $wrong = [$_POST['ans_2'],$_POST['ans_3'],$_POST['ans_4']];
    $right = $_POST['correct_ans'];
    $author = $_POST['author'];
    $withpic = $_POST['with_pic'];
    $picurl = $_POST['picurl'];
    $classify = $_POST['classify'];
    
    $ip = getIP();
    
    $bingo = rand(1,4);
    $ans = array();
    for($i=0;$i<=3;$i++){
        if ($i==$bingo-1){
            $ans[$i]=addslashes($right);
        }else{
            $ans[$i]=addslashes(array_pop($wrong));
        }
    }
    
    include '../tools/tools.php';
    $db = local_db();
    $sql = "INSERT INTO `questions_con` (`q`,`ans1`,`ans2`,`ans3`,`ans4`,`bingo`,`author`,`withpic`,`pic_addr`,`label`,`ipAddress`) VALUES ('$question','$ans[0]','$ans[1]','$ans[2]','$ans[3]','$bingo','$author','$withpic','$picurl','$classify','$ip')";
    $r = $db->query($sql);
    
    if($r==true) echo '1';
    else echo '2';
}
